package com.zoro.barn.commons.db.autopage;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.zoro.barn.commons.foundation.web.PageResultInfoInterface;
import com.zoro.barn.commons.tools.json.JsonUtil;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author zhaoxingwu
 */
public class PageList<T> extends ArrayList<T> implements PageResultInfoInterface<T> {
    private static final long serialVersionUID = -8396135432037123544L;
    private final int current;
    private final long count;

    public PageList(Collection<? extends T> c, int current, long count) {
        super(c);
        this.current = current;
        this.count = count;
    }

    public int getCurrent() {
        return current;
    }

    public long getCount() {
        return count;
    }

    public static <NT> PageList<NT> fromCollection(Collection<?> data, Class<NT> ntClass) throws JsonProcessingException {
        if (CollectionUtils.isEmpty(data)) {
            return null;
        }
        Collection<NT> ntCollection = JsonUtil.transformType(data, ntClass);
        if (data instanceof PageList<?> nList) {
            int current = nList.getCurrent();
            long count = nList.getCount();
            return new PageList<>(ntCollection, current, count);

        }
        return new PageList<>(ntCollection, 0, 0);
    }
}
